<template>
  <div>
    <div class="search">
      <input
        v-model="keyword"
        :placeholder="searchWord"
        type="text"
        class="search-input"
        @focus="searchKey"
        @blur="searchOk"
      />
    </div>
    <!-- 如果有搜索关键字才显示搜索列表 -->
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
          class="search-item"
          v-for="item in list"
          :key="item.id"
          @click="checkCity(item.name)"
        >{{item.name}}</li>
        <!-- 如果没有找到匹配的数据则显示下面的li标签 -->
        <li class="search-item" v-show="hasList">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'citySearch',
  data() {
    return {
      keyword: '',
      searchWord: '输入城市名或拼音',
      list: [], // 存放搜索的数组
      timer: null
    }
  },
  methods: {
    searchKey() {
      this.searchWord = ''
    },
    searchOk() {
      if (!this.keyword) {
        this.searchWord = '输入城市名或拼音'
      }
    },
    checkCity(city) {
      // alert(city)
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  props: {
    // 接收父组件传过来的城市数组
    cities: {
      type: Object,
      default: () => {
        return ''
      }
    }
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 当没有关键字时情况列表
      if (!this.keyword) {
        this.list = []
      }
      this.timer = setTimeout(() => {
        const result = []
        // 遍历接收的城市数组
        for (let i in this.cities) {
          // 遍历数组里每一个城市
          this.cities[i].forEach((value) => {
            // 如果搜索的城市在城市数组里，则新增到result这个新数组中
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        // 把result这个数组的值赋给搜索列表数组
        this.list = result
      }, 100)
    }
  },
  mounted() {
    // 使用better-scroll插件使列表可以拖拽滚动
    this.scroll = new Bscroll(this.$refs.search)
  },
  computed: {
    hasList() {
      return !this.list.length
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search
  height: 0.72rem
  padding: 0.1rem
  background: $bgColor
  .search-input
    box-sizing: border-box
    width: 100%
    line-height: 0.62rem
    text-align: center
    border-radius: 0.06rem
    color: #666
    padding: 0 0.1rem
.search-content
  position: absolute
  top: 1.68rem
  bottom: 0
  left: 0
  right: 0
  z-index: 1
  overflow: hidden
  background-color: #eee
  .search-item
    line-height: 0.62rem
    padding-left: 0.2rem
    background: #fff
    border-bottom: 0.02rem solid #ccc
    color: #666
</style>
